﻿using FreeSql;
using sys_Print.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Windows;
using System.Windows.Threading;

namespace sys_Print
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public static IFreeSql FsqlDB { get; private set; }
        public App()
        {

        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            string local = ConfigurationManager.AppSettings["LocalDataSource"];
            string server = ConfigurationManager.AppSettings["ServerDataSource"]; 
            int port = int.Parse(ConfigurationManager.AppSettings["Port"]);
            string Catalog = ConfigurationManager.AppSettings["Catalog"];
            string id = ConfigurationManager.AppSettings["UserId"];
            string password = ConfigurationManager.AppSettings["Password"];

            bool canConnectToLocal = TestConnection(local, 1433);// 内网地址
            if (canConnectToLocal)
            {
                // 连接成功，使用内网地址
                FsqlDB = new FreeSqlBuilder()
                    .UseConnectionString(FreeSql.DataType.SqlServer,
                    $"Data Source={local},{port};Initial Catalog={Catalog};User ID={id};Password={password}")
                    .Build();
            }
            else
            {                
                // 连接失败，切换到外网地址
                bool canConnectToServer = TestConnection(server, 1433);// 外网地址

                if (canConnectToServer)
                {
                    // 外网连接成功
                    FsqlDB = new FreeSqlBuilder()
                        .UseConnectionString(FreeSql.DataType.SqlServer, $"Data Source={server},{port};Initial Catalog={Catalog};User ID={id};Password={password}")
                        .Build();
                }
                else
                {
                    // 连接失败，显示提示
                    MessageBox.Show("无法连接到数据库，请检查网络连接或数据库配置。", "连接错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            // 订阅全局异常事件
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
        }

        private bool TestConnection(string serverAddress, int port)
        {
            try
            {
                using (var client = new TcpClient())
                {
                    client.Connect(serverAddress, port);
                    return client.Connected;
                }
            }
            catch (SocketException)
            {
                return false;
            }
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);

            // 在应用程序退出时释放数据库连接
            FsqlDB?.Dispose();
        }

        private void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            // 在这里处理异常，例如记录日志、显示错误信息等
            // MessageBox.Show($"An unhandled exception occurred: {e.Exception.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);

            HandyControl.Controls.Growl.Error("错误内容：" + e.Exception.Message);

            // 标记异常已处理
            e.Handled = true;
        }
    }
}
